/********************************************
* Copyrigt (C) rumi
* Module: drv_dh11.c
*********************************************/
#include "drv_dh11.h"

static const char *TAG = "drv_dh11.c";
/**************************Init Area*********************************/
static void DelayUs(uint32_t us)
{
    esp_rom_delay_us(us);
}
/*******************************************************************/

Dht11ErrorCode readDht11DataSimple(gpio_num_t gpioNum, float* temperature, float* humidity) {
    uint8_t data[5] = {0};
    
    gpio_set_direction(gpioNum, GPIO_MODE_OUTPUT);
    gpio_set_level(gpioNum, 0);
    DelayUs(18000); 
    gpio_set_level(gpioNum, 1);
    DelayUs(30);     
    gpio_set_direction(gpioNum, GPIO_MODE_INPUT);

    while(gpio_get_level(gpioNum) == 1); 
    while(gpio_get_level(gpioNum) == 0); 
    while(gpio_get_level(gpioNum) == 1);

    for(int i=0; i<40; i++) {
        while(gpio_get_level(gpioNum) == 0);
        if(gpio_get_level(gpioNum)) {
            data[i/8] |= (1 << (7 - (i%8)));
            while(gpio_get_level(gpioNum) == 1); 
        }
    }

    if(data[4] != (data[0]+data[1]+data[2]+data[3])) {
        ESP_LOGE(TAG, "Checksum error");
        return DHT11_ERROR_CHECKSUM;
    }

    *humidity = data[0];
    *temperature = data[2];
    return DHT11_OK;
    
}

/********************************************
 * End of file
*********************************************/
